package com.xn.app.muying.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.uitool.ShareBoard;
import com.xn.app.muying.uitool.ShareBoardlistener;
import com.xn.app.muying.uitool.SnsPlatform;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;

/**
 * 分享功能
 * Created by gaoge on 2017/7/31.
 */

public class Share {

    //activity对象
    public Activity mactivity = null;
    //记录缩略图的bitmap
    private Bitmap bitmap = null;
    //加载框
    private AlertDialog dialog = null;
    //诸葛io数据
    private JSONObject eventObject = null;
    //需要分享的内容ID
    private String shareID = "";
    //需要分享的内容分类
    private String shareType = "";
    //需要分享的内容标题
    private String shareTitle = "";
    //需要分享的内容简介
    private String shareContent = "";
    //需要分享的内容图片
    private String sharePic = "";
    //需要分享的新链接
    private String newURl = "";
    //分享数据组织
    private ShareBoard mShareBoard = null;
    //图片需要压缩的大小  kb单位
    private int picSize=30;

    /**
     * 构造方法
     *
     * @param activity     类对象
     * @param shareTitle   分享标题
     * @param shareContent 分享内容
     * @param sharePic     分享图片
     * @param shareID      分享内容ID
     * @param shareType    分享内容分类
     * @param newURl       分享的新链接
     */
    public Share(Activity activity, String shareTitle, String shareContent, String sharePic, String shareID, String shareType,String newURl) {
        this.mactivity = activity;
        this.shareTitle = shareTitle;
        this.shareContent = shareContent;
        this.sharePic = sharePic;
        this.shareID = shareID;
        this.shareType = shareType;
        this.newURl=newURl;
    }

    /**
     * 外部调用方法
     */
    public void startShare() {
        getBitMap();
    }

    /**
     * 下载方法
     */
    public void getBitMap() {
        dialog = new MyAlertDialog().ShowDialog(this.mactivity, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL myurl = null;
                bitmap = null;
                try {
                    myurl = new URL(sharePic);
                    HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                    bitmap = getZoomImage(bitmap, picSize);
                    loginHandler.sendEmptyMessage(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 图片的缩放方法
     *
     * @param bitmap  ：源图片资源
     * @param maxSize ：图片允许最大空间  单位:KB
     * @return
     */
    public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        // 单位：从 Byte 换算成 KB
        double currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩
        while (currentSize > maxSize) {
            // 计算bitmap的大小是maxSize的多少倍
            double multiple = currentSize / maxSize;
            // 开始压缩：将宽带和高度压缩掉对应的平方根倍
            // 1.保持新的宽度和高度，与bitmap原来的宽高比率一致
            // 2.压缩后达到了最大大小对应的新bitmap，显示效果最好
            bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple));
            currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        }
        return bitmap;
    }

    /**
     * bitmap转换成byte数组
     *
     * @param bitmap
     * @param needRecycle
     * @return
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 图片的缩放方法
     *
     * @param orgBitmap ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) {
        if (null == orgBitmap) {
            return null;
        }
        if (orgBitmap.isRecycled()) {
            return null;
        }
        if (newWidth <= 0 || newHeight <= 0) {
            return null;
        }

        // 获取图片的宽和高
        float width = orgBitmap.getWidth();
        float height = orgBitmap.getHeight();
        // 创建操作图片的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    showBroadView();
                    break;
            }
        }
    };

    /**
     * 打开分享弹窗
     */
    private void showBroadView() {
        if (mShareBoard == null) {
            mShareBoard = new ShareBoard(this.mactivity);
            List<String> platforms = JShareInterface.getPlatformList();
            if (platforms != null) {
                Iterator var2 = platforms.iterator();
                while (var2.hasNext()) {
                    String temp = (String) var2.next();
                    SnsPlatform snsPlatform = createSnsPlatform(temp);
                    mShareBoard.addPlatform(snsPlatform);
                }
            }
            mShareBoard.setShareboardclickCallback(mShareBoardlistener);
        }
        mShareBoard.show();
    }

    /**
     * 分享参数
     */
    private ShareBoardlistener mShareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, String platform) {
            //定义与事件相关的属性信息
            try {
                eventObject = new JSONObject();
                eventObject.put("分享平台", platform);
                eventObject.put("分享类别", shareType);
                eventObject.put("分享标题", shareTitle);
                if(newURl!=null&&!newURl.equals("")&&!newURl.equals("null")){
                    eventObject.put("分享内容链接", newURl);
                }
                eventObject.put("分享内容", APIMethod.EducationDetails(shareID));
                ZhugeSDK.getInstance().track(mactivity, "分享功能", eventObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //这里分享链接
            ShareParams shareParams = new ShareParams();
            shareParams.setShareType(Platform.SHARE_WEBPAGE);
            shareParams.setTitle(shareTitle);
            //判断内容是否为空
            if(shareContent.equals("null")){
                shareContent="";
            }
            shareParams.setText(shareContent);
            //判断是否分享其他内容
            if(newURl!=null&&!newURl.equals("")&&!newURl.equals("null")){
                shareParams.setUrl(newURl);
            }else{
                shareParams.setUrl(APIMethod.EducationDetails(shareID, true));
            }
            //判断分享平台
            if (platform.replace(" ", "").equals("QQ") || platform.replace(" ", "").equals("QZone")) {
                shareParams.setImageUrl(sharePic);
            } else {
                shareParams.setImageData(bitmap);
            }
            //分享
            JShareInterface.share(platform, shareParams, mShareListener);
        }
    };

    /**
     * 分享回调
     */
    private PlatActionListener mShareListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + error.getMessage();
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    /**
     * 判断分享的目标应用
     *
     * @param platformName
     * @return
     */
    public static SnsPlatform createSnsPlatform(String platformName) {
        String mShowWord = platformName;
        String mIcon = "";
        String mGrayIcon = "";
        String mKeyword = platformName;
        if (platformName.equals(Wechat.Name)) {
            mIcon = "jiguang_socialize_wechat";
            mGrayIcon = "jiguang_socialize_wechat";
            mShowWord = "jiguang_socialize_text_weixin_key";
        } else if (platformName.equals(WechatMoments.Name)) {
            mIcon = "jiguang_socialize_wxcircle";
            mGrayIcon = "jiguang_socialize_wxcircle";
            mShowWord = "jiguang_socialize_text_weixin_circle_key";

        } else if (platformName.equals(WechatFavorite.Name)) {
            mIcon = "jiguang_socialize_wxfavorite";
            mGrayIcon = "jiguang_socialize_wxfavorite";
            mShowWord = "jiguang_socialize_text_weixin_favorite_key";

        } else if (platformName.equals(SinaWeibo.Name)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_key";
        } else if (platformName.equals(SinaWeiboMessage.Name)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_msg_key";
        } else if (platformName.equals(QQ.Name)) {
            mIcon = "jiguang_socialize_qq";
            mGrayIcon = "jiguang_socialize_qq";
            mShowWord = "jiguang_socialize_text_qq_key";

        } else if (platformName.equals(QZone.Name)) {
            mIcon = "jiguang_socialize_qzone";
            mGrayIcon = "jiguang_socialize_qzone";
            mShowWord = "jiguang_socialize_text_qq_zone_key";
        }
        return ShareBoard.createSnsPlatform(mShowWord, mKeyword, mIcon, mGrayIcon, 0);
    }

    /**
     * 分享状态更新
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            Toast.makeText(mactivity, toastMsg, Toast.LENGTH_SHORT).show();
        }
    };
}
